package com.unnamed.b.atv.sample.holder;

import com.unnamed.b.atv.model.TreeNode;
import com.unnamed.b.atv.sample.ResourceTable;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.components.Component;
import ohos.agp.components.Checkbox;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.AbsButton;
import ohos.app.Context;

/**
 * SelectableHeaderHolder
 *
 * @author Administrator
 * @Date 2021/5/26
 */
public class SelectableHeaderHolder extends TreeNode.BaseNodeViewHolder<IconTreeItemHolder.IconTreeItem> {
    private Image arrowView;
    private Checkbox nodeSelector;

    public SelectableHeaderHolder(Context context) {
        super(context);
    }

    @Override
    public Component createNodeView(final TreeNode node, IconTreeItemHolder.IconTreeItem value) {
        Component component = LayoutScatter.getInstance(context).parse
                (ResourceTable.Layout_selectable_header, null, false);
        Text tvValue = (Text) component.findComponentById(ResourceTable.Id_node_value);
        tvValue.setText(value.getText());
        final Image iconView = (Image) component.findComponentById(ResourceTable.Id_icon);
        iconView.setPixelMap(ResourceTable.Media_folder_close);
        arrowView = (Image) component.findComponentById(ResourceTable.Id_arrow_icon);
        if (node.isLeaf()) {
            arrowView.setVisibility(Component.HIDE);
        }
        nodeSelector = (Checkbox) component.findComponentById(ResourceTable.Id_node_selector);
        nodeSelector.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(AbsButton absButton, boolean isChecked) {
                node.setSelected(isChecked);
                for (TreeNode n : node.getChildren()) {
                    getTreeView().selectNode(n, isChecked);
                }
            }
        });
        nodeSelector.setChecked(node.isSelected());
        return component;
    }

    @Override
    public void toggle(boolean active) {
        // 更新资源文件
        arrowView.setPixelMap(active ? ResourceTable.Media_arrow_down : ResourceTable.Media_arrow_right);
    }

    @Override
    public void toggleSelectionMode(boolean editModeEnabled) {
        nodeSelector.setVisibility(editModeEnabled ? Component.VISIBLE : Component.HIDE);
        nodeSelector.setChecked(mNode.isSelected());
    }
}
